import { userLogin, getInfo, logout } from '@/api/login'
import { unread } from "@/api/notice";
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo, setUserInfo, removeUserInfo, filterDynamicRoutes } from '@/utils/route'
import router, { resetRouter, constantRoutes } from '@/router'


const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: getUserInfo(),
    noticeNum: "",
    sidebarRouters: []
  }
}
const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    const dynamicRoutes = filterDynamicRoutes(userInfo.routes);
    state.sidebarRouters = constantRoutes.concat(dynamicRoutes);
    [...dynamicRoutes, { path: '*', redirect: '/404', hidden: true }].forEach(item => router.addRoute(item))
  },
  SET_NOTICE_NUM(state, num) {
    state.noticeNum = num
  },
}

const actions = {
  // 用户登录
  login({ commit }, loginForm) {
    const form = new FormData();
    for (const key in loginForm) {
      if (loginForm.hasOwnProperty(key)) {
        form.append(key, loginForm[key]);
      }
    }

    return new Promise((resolve, reject) => {
      userLogin(form).then(resp => {
        const { data } = resp
        commit('SET_TOKEN', data.token) // 提交vuex
        commit("SET_USER_INFO", data)
        setToken(data.token) // 保存本地
        setUserInfo(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(resp => {
        commit("SET_USER_INFO", resp.data)
        resolve(resp)
      }).catch(error => {
        reject(error)
      })
    })
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // 移除token
        removeUserInfo()
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // 移除token
      commit('RESET_STATE')
      resolve()
    })
  },

  unread({ commit }) {
    return new Promise(resolve => {
      unread().then(resp => {
        commit('SET_NOTICE_NUM', resp.data > 100 ? "99+" : resp.data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

